import React from 'react'
import CSSModules from 'react-css-modules'
import styles from './preview.css'
import { intlShape, injectIntl } from 'react-intl'

@injectIntl
@CSSModules(styles, { allowMultiple: true })
export default class Preview extends React.Component {
  static propTypes = {
    id: React.PropTypes.number,
    date: React.PropTypes.number,
    description: React.PropTypes.string,
    title: React.PropTypes.string,
    auther: React.PropTypes.string,
    push: React.PropTypes.func,
    intl: intlShape.isRequired
  }

  handleNavigate(id, e) {
    e.preventDefault()

    // 使用 react-router-redux 提供的方法跳转，以便更新对应的 store
    this.props.push(`/detail/${id}`)
  }
  getTime(dis) {
    const { formatDate } = this.props.intl
    const time = dis / 1000
    const hour = Math.floor(time / (60 * 60))
    if (hour && hour < 24) return hour + '小时前'
    if (hour >= 24) return formatDate(this.props.date)
    const minutes = Math.floor(time / 60)
    if (minutes) return minutes + '分钟前'
    return '刚刚'
  }
  render() {
    const dateNow = Date.now()
    const dis = dateNow - this.props.date
    const date = this.getTime(dis)
    return (
      <article styleName='article' onClick={e => this.handleNavigate(this.props.id, e)}>
        <h1 styleName='title'>
          <a>
            {this.props.title}
          </a>
        </h1>
        <p styleName='desc'>{this.props.description}</p>
        <span styleName='date'>
          <span styleName='author'>{this.props.auther}</span>{date}
        </span>
      </article>
    )
  }
}
